package xyz.hubery.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    /**
     * 自定义 RedisTemplate，使用 String 序列化 key，Jackson 序列化 value
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        // 1. 配置 Key 的序列化器（String 序列化，保证 key 可读性）
        RedisSerializer<String> stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);

        // 2. 配置 Value 的序列化器（Jackson 序列化，替代默认 JDK 序列化）
        RedisSerializer<Object> jacksonSerializer = redisSerializer();
        redisTemplate.setValueSerializer(jacksonSerializer);
        redisTemplate.setHashValueSerializer(jacksonSerializer);


        redisTemplate.setValueSerializer(jacksonSerializer);
        redisTemplate.setHashValueSerializer(jacksonSerializer);


        // 初始化 RedisTemplate 配置
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    /**
     * 创建 Jackson 序列化器，支持 Java 8 时间类型（LocalDateTime 等）
     */
    @Bean
    public RedisSerializer<Object> redisSerializer() {
        // 初始化 ObjectMapper，解决 Java 8 时间序列化、多态类型识别问题
        ObjectMapper objectMapper = new ObjectMapper()
                // 支持多态类型（如 List<Object> 中不同子类的序列化）
                .activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL)
                // 注册 Java 8 时间模块（解决 LocalDateTime 序列化失败问题）
                .registerModule(new JavaTimeModule());

        // 创建 Jackson 序列化器并绑定 ObjectMapper
        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
        serializer.setObjectMapper(objectMapper);
        return serializer;
    }
}